import Cookies from 'js-cookie'
import { getCurrentOrgs } from '@/api/org'
import { getCountryList } from '@/api/user'
import { getTaskList } from '@/api/app'

const modules = import.meta.glob('/src/assets/images/head-logo/*.png', {
  eager: true
})

let avatars = []

for (const key in modules) {
  avatars.push({
    src: modules[key].default,
    name: key.replace(/^.*[\\\/]/, '')
  })
}

const fetchTaskRequest = (commit) => {
  const date = new Date()
  date.setMilliseconds(0)
  const nowTime = Number(date.getTime() / 1000)
  const beginTime = Number(nowTime - 4 * 60 * 60)
  getTaskList({ startTime: beginTime }).then((res) => {
    commit('SET_TASKS', res)
  })
}
const taskStatus = {
  FAILED: [3, 0],
  SUCCESS: 1,
  PENDING: [5, 7, 9]
}
const state = {
  sidebar: {
    opened: Cookies.get('sidebarStatus')
      ? !!+Cookies.get('sidebarStatus')
      : true,
    withoutAnimation: false
  },
  countries: [],
  device: 'desktop',
  orgs: [],
  avatars,
  documentClientHeight: 0,
  keepAliveList: ['RemoteDesk', 'RealTimeMonitor'],
  activeDevices: [],
  tasksTimer: null,
  completed: 0,
  tasks: [],
  taskProgressClosed: true,
  flyDeskParameter: {
    compress: 0,
    quality: 0
  }
}

const getters = {
  completedTasks: (state) => {
    return state.tasks.filter((_) => _.status === taskStatus.SUCCESS).length
  }
}
const mutations = {
  TOGGLE_SIDEBAR: (state) => {
    state.sidebar.opened = !state.sidebar.opened
    state.sidebar.withoutAnimation = false
    if (state.sidebar.opened) {
      Cookies.set('sidebarStatus', 1)
    } else {
      Cookies.set('sidebarStatus', 0)
    }
  },
  CLOSE_SIDEBAR: (state, withoutAnimation) => {
    Cookies.set('sidebarStatus', 0)
    state.sidebar.opened = false
    state.sidebar.withoutAnimation = withoutAnimation
  },
  TOGGLE_DEVICE: (state, device) => {
    state.device = device
  },
  UPDATE_DOCUMENT_CLIENT_HEIGHT(state, height) {
    state.documentClientHeight = height
  },
  SET_COUNTRIES: (state, countries) => {
    state.countries = countries
  },
  SET_ORGANIZATIONS: (state, orgs) => {
    state.orgs = orgs
  },
  SET_ACTIVE_DEVICES: (state, device) => {
    const index = state.activeDevices.findIndex((v) => v.type === device.type)
    if (index === -1) {
      state.activeDevices.push(device)
    }
  },
  SET_FLY_DESK_PARAMETER(state, parameter) {
    state.flyDeskParameter = parameter
  },
  POP_ACTIVE_DEVICE: (state, { sn, type }) => {
    const index = state.activeDevices.findIndex(
      (device) => device.sn === sn && device.type === type
    )
    if (index > -1) {
      state.activeDevices.splice(index, 1)
    }
  },
  ADD_KEEP_ALIVE_LIST(state, name) {
    state.keepAliveList.indexOf(name) < 0 && state.keepAliveList.push(name)
  },
  REMOVE_KEEP_ALIVE_LIST(state, name) {
    state.keepAliveList = state.keepAliveList.filter((v) => {
      return v !== name
    })
  },
  RESET_KEEP_ALIVE_LIST(state) {
    state.keepAliveList = ['RemoteDesk', 'RealTimeMonitor']
  },
  CLEAR_KEEP_ALIVE_LIST(state, name) {
    state.keepAliveList = []
  },
  CLOSE_TASK_PROGRESS(state) {
    state.taskProgressClosed = true
  },
  OPEN_TASK_PROGRESS(state) {
    state.taskProgressClosed = false
  },
  CLEAR_TASKS_TIMER(state, timer) {
    clearInterval(state.tasksTimer)
    state.tasksTimer = null
  },
  SET_TASKS(state, tasks) {
    state.tasks = tasks.data.map((_) => ({
      ..._,
      percentage: Number(
        ((_.processCount / _.taskDetailCount) * 100).toFixed(2)
      )
    }))
  },
  CLEAR_TASKS(state) {
    state.tasks = []
  },
  SET_TASKS_TIMER(state, timer) {
    state.tasksTimer = timer
  }
}

const actions = {
  fetchTaskData(context) {
    if (!context.state.tasksTimer) {
      fetchTaskRequest(context.commit)
      context.commit('OPEN_TASK_PROGRESS')
      const interval = setInterval(() => {
        if (context.getters.completedTasks !== context.state.tasks.length) {
          fetchTaskRequest(context.commit)
        } else {
          context.commit('CLEAR_TASKS_TIMER')
        }
      }, 2000)
      context.commit('SET_TASKS_TIMER', interval)
    } else {
      context.commit('CLEAR_TASKS_TIMER')
    }
  },
  clearTasks({ commit }) {
    commit('CLEAR_TASKS')
    commit('CLOSE_TASK_PROGRESS')
    commit('CLEAR_TASKS_TIMER')
  },
  toggleSideBar({ commit }) {
    commit('TOGGLE_SIDEBAR')
  },
  closeSideBar({ commit }, { withoutAnimation }) {
    commit('CLOSE_SIDEBAR', withoutAnimation)
  },
  toggleDevice({ commit }, device) {
    commit('TOGGLE_DEVICE', device)
  },
  setCountries({ commit }) {
    return new Promise((resolve, reject) => {
      getCountryList()
        .then((res) => {
          commit('SET_COUNTRIES', res)
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  getOrgs({ commit }) {
    return new Promise((resolve, reject) => {
      getCurrentOrgs()
        .then((res) => {
          commit('SET_ORGANIZATIONS', res)
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
